﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SocketClient
{
    public partial class Form1 : Form
    {
        private Socket socketClient = null;
        private string linebreak = "\r\n";
        private Dictionary<string, string> dic = new Dictionary<string, string>();
        public Form1()
        {
            InitializeComponent();
            InitData();
        }
        private void InitData()
        {
            GetNativeIp();
            text_port.Text = "8080";
    
        }
        /// <summary>
        /// 获取ip
        /// </summary>
        public void GetNativeIp()
        {
            IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName());
            foreach (var ip in hostEntry.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    text_ipaddress.Text = ip.ToString();
                }
            }
        }

        private void btn_start_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(text_port.Text))
            {
                socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socketClient.Connect(new IPEndPoint(IPAddress.Parse(text_ipaddress.Text.Trim()), int.Parse(text_port.Text.Trim())));
                Thread t = new Thread(Recive);
                t.IsBackground = true;
                t.Start();
                text_records.AppendText("---连接成功---"+DateTime.Now.ToString() + linebreak);
                btn_start.Enabled = false;
                btn_start.BackColor = Color.Green;
               

            }
            else MessageBox.Show("请填写端口", "提示", MessageBoxButtons.OK);
        }

        private void Recive()
        {
            while (true)
            {
                try
                {
                    byte[] buffer = new byte[1024 * 1024 * 2];
                    int length = socketClient.Receive(buffer);//将收到的数据存入缓存区并返回收到的字节数
                    string reciveString = Encoding.UTF8.GetString(buffer).Replace("\0", "");
                    //接受连接用户信息
                    if (reciveString.Contains("type=1")) {
                        reciveString = reciveString.Replace("type=1", "");
                        dic = JsonConvert.DeserializeObject<Dictionary<string,string>>(reciveString);
                        Invoke(new Action(() =>
                        {
                            listView1.Items.Clear();
                            foreach (var item in dic)
                            {
                                ListViewItem item1 = new ListViewItem(item.Key);
                                item1.SubItems.Add(item.Value);
                                listView1.Items.Add(item1);
                            }
                            label_count.Text = listView1.Items.Count.ToString();
                        }));
                       

                    }
                   else  text_records.Invoke(new Action(() =>
                    {
                        text_records.AppendText(DateTime.Now.ToString() + linebreak  + $"{reciveString}" + linebreak);
                    }));

                }
                catch(Exception e)
                {
                    text_records.Invoke(new Action(() =>
                    {
                         text_records.AppendText(DateTime.Now.ToString() + linebreak + socketClient.RemoteEndPoint.ToString() + $":{e.Message}" + linebreak);
                    }));
                    return;
                }


            }
        }
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="message"></param>
        private void send(string message)
        {
            byte[] data = Encoding.UTF8.GetBytes(message);
            socketClient.Send(data);
        }

        private void btn_send_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(text_send.Text))
            {
                send(text_send.Text.Trim());
                text_records.AppendText( DateTime.Now.ToString() + linebreak+ "我:" + $"{text_send.Text.Trim()}"+linebreak);
                text_send.Text = string.Empty;
            }
            else MessageBox.Show("请输入内容", "提示", MessageBoxButtons.OK);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Application.Restart();
        }
    }
}
